package login;

import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

public class GetBack {
    /**
     * 功能：实现忘记密码
     * 让用户输入用户名和手机号
     * 二者相同：
     * 让用户输入新密码，并更新文件
     */
    //用户数据文件路径
    private static final String user_file = "File\\User.txt";
    //忘记密码功能主方法
    public void getBack(){
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名:");
        String userName = sc.next();
        System.out.println("请输入手机号:");
        String phoneNumber = sc.next();
        if(verifyUser(userName,phoneNumber)){
            System.out.println("请输入新密码");
            String newPassword = sc.next();
            updatePassword(userName,newPassword);
            System.out.println("密码更新成功");
        }else{
            System.out.println("验证失败，用户名和手机号不相符");
        }
    }

    /**
     * =======================
     * 辅助方法
     * @param
     */

    //验证用户名和手机号是否相符合
    public boolean verifyUser(String userName,String phoneNumber) {
        try {
            BufferedReader reader = new BufferedReader(new FileReader(user_file));
            String line;
            while ((line = reader.readLine()) != null) {
                String[] parts = line.split(":");
                if (parts.length == 3 && parts[0].equals(userName) && parts[2].equals(phoneNumber)) {
                    System.out.println("验证正确");
                    return true;
                }

            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }

    //修改密码
    public void updatePassword(String userName,String newPassword){
        String line;
        File file =new File(user_file);
        try (BufferedReader reader = new BufferedReader(new FileReader(user_file));
            BufferedWriter writer = new BufferedWriter(new FileWriter(user_file,true)))
            {
                    while ((line = reader.readLine()) != null)
                    {
                        String[] parts = line.split(":");
                        if (parts.length == 3 && parts[0].equals(userName))
                        {
                            writer.write(parts[0] + ":" + newPassword + ":" +parts[2] );
                            writer.newLine();
                        }
                    }
                    writer.flush();
            }catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}